package com.zhxin.nettylab.decoder.chapter2;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * @ClassName StringIntegerDecoder
 * @Description //实现Header-Content协议传输分包的字符串内容解码器
 * @Author singleZhang
 * @Email 405780096@qq.com
 * @Date 2020/12/7 0007 下午 3:29
 **/
public class StringIntegerDecoder extends ByteToMessageDecoder {



    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws UnsupportedEncodingException {

        //可读字节小于4
        if(in.readableBytes() < 4){
            return;
        }

        //设置消息头的readIndex读指针位置 为回滚点
        in.markReaderIndex();
        int length = in.readInt();
        if(in.readableBytes() < length){

            in.resetReaderIndex();//重置,退出
            return;
        }
        byte[] bytes = new byte[length];
        in.readBytes(bytes,0,length);
        out.add(new String(bytes,"UTF-8"));
    }

}
